package com.jiuzhe.commercial.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.bean.CityBean;

import java.util.List;

/**
 * Created by huanghao on 2018/5/11.
 */

public class CityListAdapter extends RecyclerView.Adapter<CityListAdapter.ViewHolder> {
    private MyItemClickListener mItemClickListener;
    private List<CityBean> list;

    public CityListAdapter(List<CityBean> list2) {
        this.list = list2;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_city_item, parent, false);
        // 实例化viewholder
        ViewHolder viewHolder = new ViewHolder(v, mItemClickListener);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.tv_city.setText(list.get(position).getCityName());
    }


    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private MyItemClickListener mListener;
        TextView tv_city;

        public ViewHolder(View v, MyItemClickListener myItemClickListener) {
            super(v);
            //将全局的监听赋值给接口
            this.mListener = myItemClickListener;
            v.setOnClickListener(this);
            tv_city = (TextView) v.findViewById(R.id.tv_city);
        }

        /**
         * 实现OnClickListener接口重写的方法
         *
         * @param v
         */
        @Override
        public void onClick(View v) {
            if (mListener != null) {
                mListener.onItemClick(v, getPosition());
            }
        }
    }

    /**
     * 创建一个回调接口
     */
    public interface MyItemClickListener {
        void onItemClick(View view, int position);
    }

    /**
     * 在activity里面adapter就是调用的这个方法,将点击事件监听传递过来,并赋值给全局的监听
     *
     * @param myItemClickListener
     */
    public void setItemClickListener(MyItemClickListener myItemClickListener) {
        this.mItemClickListener = myItemClickListener;
    }
}
